package fun.hijklmn.magic.admin.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import fun.hijklmn.magic.admin.common.pojo.User;
import fun.hijklmn.magic.admin.common.vo.req.UserReqVO;
import fun.hijklmn.magic.admin.server.dao.UserDao;
import fun.hijklmn.magic.admin.server.properties.AdminProperties;
import fun.hijklmn.magic.admin.server.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import fun.hijklmn.magic.common.enums.StatusEnum;
import fun.hijklmn.magic.common.exception.MagicBizException;
import fun.hijklmn.magic.common.utils.AesSecurityUtil;
import fun.hijklmn.magic.idGenerator.client.api.IdGeneratorServiceApi;
import fun.hijklmn.magic.idGenerator.common.enums.ServerTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zsl
 * @since 2021-06-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    private AdminProperties adminProperties;

    @Autowired
    private IdGeneratorServiceApi idGeneratorServiceApi;

    @Override
    public User save(UserReqVO userReqVO) {

        LocalDateTime curLocalDateTime = LocalDateTime.now();

        if (userReqVO.getStatus() != null && !StatusEnum.AdminRoleStatusEnum.containStatus(userReqVO.getStatus())) {
            throw new MagicBizException("状态错误");
        }

        if (StringUtils.isNotEmpty(userReqVO.getUserName()) || StringUtils.isNotEmpty(userReqVO.getCellphone()) || StringUtils.isNotEmpty(userReqVO.getEMail())) {

            QueryWrapper<User> userQueryWrapper1 = new QueryWrapper<>();

            userQueryWrapper1.eq("is_delete", 0);

            StringBuilder stringBuilder = new StringBuilder(" (");

            if (StringUtils.isNotEmpty(userReqVO.getUserName())) {
                stringBuilder.append("user_name = '" + userReqVO.getUserName() + "'");
            }

            if (StringUtils.isNotEmpty(userReqVO.getEMail())) {
                if (stringBuilder.length() > 5) {
                    stringBuilder.append(" or ");
                }
                stringBuilder.append("e_mail = '" + userReqVO.getEMail() + "'");
            }

            if (StringUtils.isNotEmpty(userReqVO.getCellphone())) {
                if (stringBuilder.length() > 5) {
                    stringBuilder.append(" or ");
                }
                stringBuilder.append("cellphone = '" + userReqVO.getCellphone() + "' ");
            }

            stringBuilder.append(")");

            userQueryWrapper1.apply(stringBuilder.toString());

            userQueryWrapper1.select("id", "user_name", "cellphone", "e_mail");

            List<User> userList = this.list(userQueryWrapper1);

            if (StringUtils.isEmpty(userReqVO.getId()) && !CollectionUtils.isEmpty(userList)) {

                User user1 = userList.get(0);

                if (StringUtils.isNotEmpty(user1.getCellphone()) && user1.getCellphone().equals(userReqVO.getCellphone())) {
                    throw new MagicBizException("该电话号码已经被使用");
                }

                if (StringUtils.isNotEmpty(user1.getEMail()) && user1.getEMail().equals(userReqVO.getEMail())) {
                    throw new MagicBizException("该邮箱已经被使用");
                }

                if (StringUtils.isNotEmpty(user1.getUserName()) && user1.getUserName().equals(userReqVO.getUserName())) {
                    throw new MagicBizException("该用户名已经被使用");
                }

            }

            List<User> repeatUserList = userList.stream().filter(user1 -> user1.getId().equals(userReqVO.getId())).collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(repeatUserList)) {

                User user1 = repeatUserList.get(0);

                if (StringUtils.isNotEmpty(user1.getCellphone()) && user1.getCellphone().equals(userReqVO.getCellphone())) {
                    throw new MagicBizException("该电话号码已经被使用");
                }

                if (StringUtils.isNotEmpty(user1.getEMail()) && user1.getEMail().equals(userReqVO.getEMail())) {
                    throw new MagicBizException("该邮箱已经被使用");
                }

                if (StringUtils.isNotEmpty(user1.getUserName()) && user1.getUserName().equals(userReqVO.getUserName())) {
                    throw new MagicBizException("该用户名已经被使用");
                }


            }

        }

        if (StringUtils.isNotEmpty(userReqVO.getId())) {

            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("is_delete", 0);
            userQueryWrapper.eq("id", userReqVO.getId());
            User user = this.getOne(userQueryWrapper);

            if (user == null || user.getIsDelete()) {
                throw new MagicBizException("该用户已经删除");
            }

            User updateUser = new User();
            BeanUtils.copyProperties(userReqVO, updateUser);
            updateUser.setUpdateTime(curLocalDateTime);
            this.update(updateUser, new UpdateWrapper<User>().eq("id", userReqVO.getId()));

            return updateUser;

        } else {

            if (StringUtils.isNotEmpty(userReqVO.getPassword())) {
                throw new MagicBizException("请设置密码");
            }

            User insertUser = new User();

            BeanUtils.copyProperties(userReqVO, insertUser);

            insertUser.setCreateTime(curLocalDateTime);

            insertUser.setPassword(AesSecurityUtil.encrypt(adminProperties.getAesKey(), insertUser.getPassword()));

            insertUser.setStatus(StatusEnum.AdminRoleStatusEnum.normal.status());

            insertUser.setIsDelete(StatusEnum.RecordValidEnum.normal.isDelete());

            insertUser.setId(idGeneratorServiceApi.get(ServerTypeEnum.admin_server));

            this.save(insertUser);

            return insertUser;

        }

    }

}
